function toast(msg){
  wx.showToast({
    title: msg,
    icon: 'none'
  })
}
function requestor(){
  function request(option){
    option.header = {
      'content-type': 'application/json; charset=utf-8'
    }
    if(option.addToHeader){
      option.header.Authorization = wx.getStorageSync('tokenHead') +  wx.getStorageSync('token')
    }
	let options = Object.assign({},option)
    options.addToHeader && delete options.addToHeader
    return new Promise(function (resolve, reject) { 
      wx.request({
        ...options,
        success (res) {
          const { statusCode, data } = res
          const errno = data.errno + ''
          if(statusCode && (errno.substring(0, 4) == '3004') ){
            wx.removeStorageSync('token')
            wx.removeStorageSync('tokenHead')
            wx.removeStorageSync('openId')
            // wx.navigateTo({
            //   url: "/pages/login/index"
            // })
          }
          if(data.ok){
            data? resolve(data) : resolve([])
          }else {
            reject(data)
            toast(data.errmsg)
          }
        },
        fail (res) {
          reject(res)
          toast("服务器错误")
        }
      })
    })
  }
  function requestPost(apiOption,data) {
    apiOption.method = 'POST'
    apiOption.data = data
    return request(apiOption)
  }
  function requestGet (apiOption,data) {
    apiOption.method = 'GET'
    apiOption.data = data
    return request(apiOption)
  }
  return {
    requestPost,
    requestGet,
  }
}
module.exports = requestor
